package com.kairos.jetparksample.domain

import androidx.lifecycle.*
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewmodel.CreationExtras
import com.kairos.jetparksample.MyApplication
import com.kairos.jetparksample.data.repository.Repository

/**
 *@Author Nick.wu
 *Date 2023/6/14
 */
class SaveStateViewModelSample(private val myRepository: Repository,
                               private val savedStateHandle: SavedStateHandle
): ViewModel() {

    companion object {
        val Factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory {
            @Suppress("UNCHECKED_CAST")
            override fun <T : ViewModel> create(
                modelClass: Class<T>,
                extras: CreationExtras
            ): T {
                //获取到application
                val application = checkNotNull(extras[APPLICATION_KEY])
                val savedStateHandle = extras.createSavedStateHandle()
                return SaveStateViewModelSample(
                    (application as MyApplication).myRepository,
                    savedStateHandle
                ) as T
            }
        }
    }
}